package cn.yuanqiao.archive.danganzhengli.service.impl;

import java.io.*;
import java.net.URL;
import java.util.Date;
import java.util.List;

import cn.yuanqiao.archive.appManager.domain.TenantCategory;
import cn.yuanqiao.archive.appManager.mapper.TenantCategoryMapper;
import cn.yuanqiao.archive.appManager.service.ITenantSysConfigService;
import cn.yuanqiao.archive.danganzhengli.domain.ArchivePack;
import cn.yuanqiao.archive.danganzhengli.domain.PackDetail;
import cn.yuanqiao.archive.danganzhengli.mapper.ArchivePackMapper;
import cn.yuanqiao.archive.danganzhengli.service.IArchivePackService;
import cn.yuanqiao.archive.danganzhengli.service.IHandOverReceiveService;
import cn.yuanqiao.common.core.context.ResponseUtils;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.SecurityUtils;
import cn.yuanqiao.common.utils.SnowflakeIdGenerator;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.common.utils.ZipUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import javax.xml.crypto.Data;


/**
 * 打包日志Service业务层处理
 *
 * @author xy
 * @date 2024-09-13
 */
@Service
public class ArchivePackServiceImpl implements IArchivePackService
{
    @Autowired
    private ArchivePackMapper archivePackMapper;

    @Autowired
    private IHandOverReceiveService handOverReceiveService;
    @Autowired
    private ITenantSysConfigService sysConfigService;

    @Autowired
    private TenantCategoryMapper tenantCategoryMapper;
    /**
     * 查询打包日志
     *
     * @param id 打包日志主键
     * @return 打包日志
     */
    @Override
    public ArchivePack selectArchivePackById(Long id)
    {
        return archivePackMapper.selectArchivePackById(id,new ArchivePack().getTableName(),SecurityUtils.getTenantCode());
    }

    /**
     * 查询打包日志列表
     *
     * @param archivePack 打包日志
     * @return 打包日志
     */
    @Override
    public List<ArchivePack> selectArchivePackList(ArchivePack archivePack)
    {
        return archivePackMapper.selectArchivePackList(archivePack,SecurityUtils.getTenantCode());
    }

    /**
     * 新增打包日志
     *
     * @param archivePack 打包日志
     * @return 结果
     */
    @Transactional
    @Override
    public int insertArchivePack(ArchivePack archivePack)
    {
        int rows = archivePackMapper.insertArchivePack(archivePack);
        insertPackDetail(archivePack);
        return rows;
    }

    /**
     * 修改打包日志
     *
     * @param archivePack 打包日志
     * @return 结果
     */
    @Transactional
    @Override
    public int updateArchivePack(ArchivePack archivePack)
    {
        archivePackMapper.deletePackDetailByPID(archivePack.getId());
        insertPackDetail(archivePack);
        return archivePackMapper.updateArchivePack(archivePack);
    }

    /**
     * 批量删除打包日志
     *
     * @param ids 需要删除的打包日志主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteArchivePackByIds(Long[] ids)
    {
        archivePackMapper.deletePackDetailByPIDs(ids);
        return archivePackMapper.deleteArchivePackByIds(ids);
    }

    /**
     * 删除打包日志信息
     *
     * @param id 打包日志主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteArchivePackById(Long id)
    {
        archivePackMapper.deletePackDetailByPID(id);
        return archivePackMapper.deleteArchivePackById(id);
    }

    @Override
    public void pack(Long categoryId, Long[] ids, Integer type) {

        Long id= SnowflakeIdGenerator.generateId();
        String tenantCode=SecurityUtils.getTenantCode();
        String path = sysConfigService.selectConfigByKey("PACK_PATH");
        if(StringUtils.isEmpty(path)){
            throw new ServiceException("请查看PACK_PATH参数是否存在!");
        }

        try{
         Date startTime=new Date();

         List<PackDetail> list=new ArrayList<>();
         if(!path.endsWith("/")){
           path+="/";
         }
           String fileName=id+""+startTime.getTime()+".zip";
            //将数据新增 状态 0：失败 1：成功 2:进行中
            ArchivePack archivePack=new ArchivePack();
            archivePack.setId(id);
            archivePack.setPackTime(startTime);
            archivePack.setCategoryId(categoryId);
            archivePack.setState("2");
            archivePack.setCreateId(SecurityUtils.getUserId());
            archivePack.setPath(path);
            archivePack.setFileName(fileName);
         for(Long daId:ids){
             PackDetail packDetail=new PackDetail();
             packDetail.setId(SnowflakeIdGenerator.generateId());
             packDetail.setpId(id);
             packDetail.setDaId(daId);
             list.add(packDetail);
         }
            archivePack.setPackDetailList(list);
            insertArchivePack(archivePack);
            File packZip = new File(path + fileName);
            if (!packZip.exists()) {
                //判断该文件的上级目录是否存在
                if(!packZip.getParentFile().exists()){
                    packZip.getParentFile().mkdirs();
                }
                String packPath = path + id+""+startTime.getTime() + File.separator;
                File file = new File(packPath);
                if (file.exists()) {
                    //删除目录重新生成
                    FileUtils.deleteQuietly(file);
                }
                //通过门类ID获取档案列表
                for(Long daId:ids) {
                    handOverReceiveService.packXml(packPath, daId,type);
                }
                //打压缩包
                ZipUtils.zip(packPath, path + id+""+startTime.getTime());
                //生成后删除临时文件
                FileUtils.deleteQuietly(file);
            }

         Date endTime=new Date();
         archivePackMapper.editArchivePack(id,"1",endTime,tenantCode,1);
        }catch (Exception ex){
            //将打包状态改成失败
            archivePackMapper.editArchivePack(id,"0",null,tenantCode,null);
            ex.printStackTrace();
            throw new ServiceException("打包失败！");
        }
    }

    @Override
    public List<PackDetail> selectDetailList(Long pId) {
        ArchivePack archivePack=archivePackMapper.selectArchivePackById(pId,new ArchivePack().getTableName(),SecurityUtils.getTenantCode());
        TenantCategory tenantCategory= tenantCategoryMapper.selectTenantCategoryByID(archivePack.getCategoryId(),new TenantCategory().getTableName());
        String daTable="";
        if(tenantCategory.getType()==0){
            daTable=tenantCategory.getFileTableName();
        }else if(tenantCategory.getType()==1){
            daTable=tenantCategory.getFolderTableName();
        }else if(tenantCategory.getType()==3){
            daTable=tenantCategory.getItemTableName();
        }

        return archivePackMapper.selectDetailList(pId,daTable,new PackDetail().getTableName());
    }

    @Override
    public void downLode(Long id, HttpServletResponse response) throws IOException {
        ArchivePack archivePack= selectArchivePackById(id);
        Integer num=archivePack.getNum()==null?0:archivePack.getNum();
        BufferedInputStream br =null;
        OutputStream out =null;
        if(num<=0){
            throw new SecurityException("该包打包失败或者已进行下载,不能再次下载！");
        }
        String filePath=archivePack.getPath()+ archivePack.getFileName();
        File f = new File(filePath);
        try {

            if (!f.exists()) {
                response.sendError(404, "File not found!");
                //return ResponseData.error("File not found!");
            }
             br = new BufferedInputStream(new FileInputStream(f));
            byte[] buf = new byte[1024];
            int len = 0;
            boolean isOnLine = true;
            response.reset(); // 非常重要
            ResponseUtils.defaultResponse(response);
            String fileName = archivePack.getFileName();

            if (isOnLine) { // 在线打开方式
                URL u = new URL("file:///" + filePath);
                response.setContentType(u.openConnection().getContentType());
                response.setHeader("Content-Disposition", "inline; filename=" + fileName);
                // 文件名应该编码成UTF-8
            } else { // 纯下载方式
                response.setContentType("application/x-msdownload");
                response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            }
            out = response.getOutputStream();
            while ((len = br.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            br.close();
            out.close();
            //将下载次数进行修改
            archivePackMapper.updateNum(id,new ArchivePack().getTableName(),0);
            if(f.exists()){
                f.delete();
            }
        }catch (Exception ex){
            ex.printStackTrace();
        }finally {
            br.close();
            out.close();
        }
    }

    /**
     * 新增打包档案详情信息
     *
     * @param archivePack 打包日志对象
     */
    public void insertPackDetail(ArchivePack archivePack)
    {
        List<PackDetail> packDetailList = archivePack.getPackDetailList();
        Long id = archivePack.getId();
        if (StringUtils.isNotNull(packDetailList))
        {
            List<PackDetail> list = new ArrayList<PackDetail>();
            for (PackDetail packDetail : packDetailList)
            {
                packDetail.setpId(id);
                list.add(packDetail);
            }
            if (list.size() > 0)
            {
                archivePackMapper.batchPackDetail(list,SecurityUtils.getTenantCode());
            }
        }
    }
}
